/**
 * Copyright (c) 2020 铭软科技(mingsoft.net)
 * 本软件及相关文档文件（以下简称“软件”）的版权归 铭软科技 所有
 * 遵循铭软科技《保密协议》
 */
package net.mingsoft.mwebsite.action;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import net.mingsoft.base.entity.BaseEntity;
import net.mingsoft.base.entity.ResultData;
import net.mingsoft.base.util.JSONArray;
import net.mingsoft.basic.annotation.LogAnn;
import net.mingsoft.basic.bean.EUListBean;
import net.mingsoft.basic.biz.IModelBiz;
import net.mingsoft.basic.biz.IRoleModelBiz;
import net.mingsoft.basic.constant.e.BusinessTypeEnum;
import net.mingsoft.basic.entity.ManagerSessionEntity;
import net.mingsoft.basic.entity.ModelEntity;
import net.mingsoft.basic.entity.RoleModelEntity;
import net.mingsoft.basic.util.BasicUtil;
import net.mingsoft.basic.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 模块表管理控制层
 * @author 铭软团队
 * @version
 * 版本号：1<br/>
 * 创建日期：2017-8-23 11:26:11<br/>
 * 历史修订：<br/>
 */
@Api(value = "模块表接口")
@Controller("mweModelAction")
@RequestMapping("/${ms.manager.path}/mwebsite/model")
public class ModelAction extends BaseAction{

	/**
	 * 注入模块表业务层
	 */
	@Autowired
	private IModelBiz modelBiz;
	/**
	 * 角色模块关联业务层
	 */
	@Autowired
	private IRoleModelBiz roleModelBiz;

	/**
	 * 返回主界面index
	 */
	@ApiOperation(value = "返回主界面index")
	@GetMapping("/index")
	public String index(HttpServletResponse response,HttpServletRequest request,@ApiIgnore ModelMap mode){
		List<ModelEntity> parentModelList = modelBiz.queryAll();
		mode.addAttribute("parentModelList", JSONArray.toJSONString(parentModelList));
		return "/mwebsite/model/index";
	}

	/**
	 * 查询所有模块，以json格式输出
	 * @param response 响应对象
	 */
	@ApiOperation(value="查询所有模块，以json格式输出")
	@PostMapping("/query")
	@ResponseBody
	public ResultData query(HttpServletResponse response) {
		int roleId = BasicUtil.getInt("roleId");
		ModelEntity model = new ModelEntity();
		List<ModelEntity> modelList = modelBiz.query(model);
		List<ModelEntity> _modelList = new ArrayList<>();
		List<ModelEntity> childModelList = new ArrayList<>();
		ManagerSessionEntity managerSession = this.getManagerBySession();
		int currentRoleId = managerSession.getRoleId();
		boolean updateFalg = true;
		//新增角色roleId为0，默认当前管理员的roleId
		if(roleId == 0){
			updateFalg = false;
			roleId = currentRoleId;
		}
		List<RoleModelEntity> roleModelList = new ArrayList<>();
		if(roleId>0){
			roleModelList = roleModelBiz.queryByRoleId(roleId);
		}
		//将菜单和功能区分开
		for(BaseEntity base : modelList){
			ModelEntity _model = (ModelEntity) base;
			if(_model.getModelIsMenu() == 1){
				_model.setModelChildList(new ArrayList<ModelEntity>());
				_modelList.add(_model);
			}else if(_model.getModelIsMenu() == 0){
				childModelList.add(_model);
			}
		}
		//菜单和功能一一匹配
		for(ModelEntity _modelEntity : _modelList){
			for(ModelEntity childModel : childModelList){
				if(childModel.getModelId() == _modelEntity.getIntId()){
					_modelEntity.getModelChildList().add(childModel);
					//选中状态
					for(RoleModelEntity roleModelEntity : roleModelList){
						if(roleModelEntity.getModelId() == childModel.getIntId() && updateFalg){
							childModel.setChick(1);
						}
					}
				}
			}
		}
		EUListBean _list = new EUListBean(_modelList, _modelList.size());
		return ResultData.build().success(_list);
	}
	/**
	 * 查询模块表列表
	 * @param model 模块表实体
	 * <i>model参数包含字段信息参考：</i><br/>
	 * modelId 模块自增长id<br/>
	 * modelTitle 模块标题<br/>
	 * modelCode 模块编码<br/>
	 * modelId 模块的父模块id<br/>
	 * modelUrl 模块连接地址<br/>
	 * modelDatetime <br/>
	 * modelIcon 模块图标<br/>
	 * modelModelmanagerid 模块关联的关联员id<br/>
	 * modelSort 模块的排序<br/>
	 * modelIsmenu 模块是否是菜单<br/>
	 * <dt><span class="strong">返回</span></dt><br/>
	 * <dd>[<br/>
	 * { <br/>
	 * modelId: 模块自增长id<br/>
	 * modelTitle: 模块标题<br/>
	 * modelCode: 模块编码<br/>
	 * modelId: 模块的父模块id<br/>
	 * modelUrl: 模块连接地址<br/>
	 * modelDatetime: <br/>
	 * modelIcon: 模块图标<br/>
	 * modelModelmanagerid: 模块关联的关联员id<br/>
	 * modelSort: 模块的排序<br/>
	 * modelIsmenu: 模块是否是菜单<br/>
	 * }<br/>
	 * ]</dd><br/>	 
	 */
	@ApiOperation(value="菜单列表接口")
	@GetMapping("/list")
	@ResponseBody
	public ResultData list(@ModelAttribute @ApiIgnore  ModelEntity modelEntity,HttpServletResponse response, HttpServletRequest request,@ApiIgnore ModelMap model) {
		List modelList = modelBiz.query(modelEntity);
		EUListBean _list = new EUListBean(modelList, modelList.size());
		return ResultData.build().success(_list);
	}

	/**
	 * 获取模块表
	 * @param model 模块表实体
	 * <i>model参数包含字段信息参考：</i><br/>
	 * modelId 模块自增长id<br/>
	 * modelTitle 模块标题<br/>
	 * modelCode 模块编码<br/>
	 * modelId 模块的父模块id<br/>
	 * modelUrl 模块连接地址<br/>
	 * modelDatetime <br/>
	 * modelIcon 模块图标<br/>
	 * modelModelmanagerid 模块关联的关联员id<br/>
	 * modelSort 模块的排序<br/>
	 * modelIsmenu 模块是否是菜单<br/>
	 * <dt><span class="strong">返回</span></dt><br/>
	 * <dd>{ <br/>
	 * modelId: 模块自增长id<br/>
	 * modelTitle: 模块标题<br/>
	 * modelCode: 模块编码<br/>
	 * modelId: 模块的父模块id<br/>
	 * modelUrl: 模块连接地址<br/>
	 * modelDatetime: <br/>
	 * modelIcon: 模块图标<br/>
	 * modelModelmanagerid: 模块关联的关联员id<br/>
	 * modelSort: 模块的排序<br/>
	 * modelIsmenu: 模块是否是菜单<br/>
	 * }</dd><br/>
	 */
	@ApiOperation(value = "获取模块表")
	@ApiImplicitParam(name = "modelId", value = "模块的编号", required = true,paramType="query")
	@GetMapping("/get")
	@ResponseBody
	public ResultData get(@ModelAttribute @ApiIgnore  ModelEntity modelEntity,HttpServletResponse response, HttpServletRequest request,@ApiIgnore ModelMap model){
		if(modelEntity.getIntId() <= 0) {
			return ResultData.build().error(getResString("err.error", this.getResString("model.id")));
		}
		//根据父模块id查寻模块
		ModelEntity _model = (ModelEntity)modelBiz.getEntity(modelEntity.getIntId());
		if(_model != null){
			Map<String, ModelEntity> mode = new HashMap<String, ModelEntity>();
			if (_model.getModelId() != null){
				ModelEntity parentModel = (ModelEntity) modelBiz.getEntity(_model.getIntId());
				mode.put("parentModel", parentModel);
			}else {
				mode.put("parentModel", null);
			}
			mode.put("model", _model);
			return ResultData.build().success(_model);
		}
		return ResultData.build().success(_model);
	}

	/**
	 * 保存模块表实体
	 * @param model 模块表实体
	 * <i>model参数包含字段信息参考：</i><br/>
	 * modelId 模块自增长id<br/>
	 * modelTitle 模块标题<br/>
	 * modelCode 模块编码<br/>
	 * modelId 模块的父模块id<br/>
	 * modelUrl 模块连接地址<br/>
	 * modelDatetime <br/>
	 * modelIcon 模块图标<br/>
	 * modelModelmanagerid 模块关联的关联员id<br/>
	 * modelSort 模块的排序<br/>
	 * modelIsmenu 模块是否是菜单<br/>
	 * <dt><span class="strong">返回</span></dt><br/>
	 * <dd>{ <br/>
	 * modelId: 模块自增长id<br/>
	 * modelTitle: 模块标题<br/>
	 * modelCode: 模块编码<br/>
	 * modelId: 模块的父模块id<br/>
	 * modelUrl: 模块连接地址<br/>
	 * modelDatetime: <br/>
	 * modelIcon: 模块图标<br/>
	 * modelModelmanagerid: 模块关联的关联员id<br/>
	 * modelSort: 模块的排序<br/>
	 * modelIsmenu: 模块是否是菜单<br/>
	 * }</dd><br/>
	 */
	@ApiOperation(value = "保存模块表实体")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "modelTitle", value = "模块的标题", required = true,paramType="query"),
			@ApiImplicitParam(name = "modelCode", value = "模块编码", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelId", value = "模块父id", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelUrl", value = "链接地址", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelDatetime", value = "发布时间", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelIcon", value = "模块图标", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelManagerId", value = "模块管理员Id", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelSort", value = "模块排序", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelIsMenu", value = "是否是菜单", required = false,paramType="query"),
			@ApiImplicitParam(name = "isChild", value = "菜单类型", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelParentIds", value = "父级编号集合", required = false,paramType="query"),
	})
	@LogAnn(title = "保存模块表实体",businessType= BusinessTypeEnum.INSERT)
	@PostMapping("/save")
	@ResponseBody
	public ResultData save(@ModelAttribute @ApiIgnore  ModelEntity model, HttpServletResponse response, HttpServletRequest request) {
		//获取管理员id并赋值给模块的id
		model.setId(getManagerBySession().getId());
		// 获取模块保存时间
		model.setModelDatetime(new Timestamp(System.currentTimeMillis()));
		if (!StringUtil.checkLength(model.getModelTitle(), 1, 20) ) {
			return ResultData.build().success(getResString("err.length",this.getResString("modelTitle"),"2","20"));
		}
		//判断图标是否为空，不为空去掉,图标地址中含有的“|”
		//空值判断
		if(!StringUtil.isBlank(model.getModelIcon())) {
			model.setModelIcon( model.getModelIcon().replace("|", ""));
		}
		//重复判断，modelCode不能重复
		if(StringUtils.isNotBlank(model.getModelCode())){
			ModelEntity _model = modelBiz.getEntityByModelCode(model.getModelCode());
			if (!StringUtil.isBlank(_model)){
				return ResultData.build().error(getResString("err.exist",this.getResString("modelCode")));
			}
		}
		//添加父级id集合
		ModelEntity parent = (ModelEntity) modelBiz.getEntity(model.getIntId());
		String parentIds="";
		if(parent != null) {
			if (parent.getModelParentIds() != null) {
				parentIds = parent.getModelParentIds() + "," + model.getModelId();
			} else {
				parentIds = model.getModelId() + "";
			}
		}
		if (StringUtil.isBlank(model.getModelCode())){
			//将模块编号设置为模块编码
			model.setModelCode(model.getId());
		}
		model.setModelParentIds(parentIds);
		modelBiz.saveEntity(model);
		//返回模块id到页面
		return ResultData.build().success(model.getId());
	}

	/**
	 * <i>model参数包含字段信息参考：</i><br/>
	 * modelId:多个modelId直接用逗号隔开,例如modelId=1,2,3,4
	 * 批量删除模块表
	 *            <dt><span class="strong">返回</span></dt><br/>
	 *            <dd>{code:"错误编码",<br/>
	 *            result:"true｜false",<br/>
	 *            resultMsg:"错误信息"<br/>
	 *            }</dd>
	 */
	@ApiOperation(value = "批量删除模块表")
	@ApiImplicitParam(name = "ids", value = "模块编号，多个以逗号隔开", required = false,paramType="query")
	@LogAnn(title = "批量删除模块表",businessType= BusinessTypeEnum.DELETE)
	@GetMapping("/delete")
	@ResponseBody
	public ResultData delete() {
		int[] ids = BasicUtil.getInts("ids", ",");
		modelBiz.delete(ids);
		return ResultData.build().success();
	}

	/**
	 * 更新模块表信息模块表
	 * @param model 模块表实体
	 * <i>model参数包含字段信息参考：</i><br/>
	 * modelId 模块自增长id<br/>
	 * modelTitle 模块标题<br/>
	 * modelCode 模块编码<br/>
	 * modelId 模块的父模块id<br/>
	 * modelUrl 模块连接地址<br/>
	 * modelDatetime <br/>
	 * modelIcon 模块图标<br/>
	 * modelModelmanagerid 模块关联的关联员id<br/>
	 * modelSort 模块的排序<br/>
	 * modelIsmenu 模块是否是菜单<br/>
	 * <dt><span class="strong">返回</span></dt><br/>
	 * <dd>{ <br/>
	 * modelId: 模块自增长id<br/>
	 * modelTitle: 模块标题<br/>
	 * modelCode: 模块编码<br/>
	 * modelId: 模块的父模块id<br/>
	 * modelUrl: 模块连接地址<br/>
	 * modelDatetime: <br/>
	 * modelIcon: 模块图标<br/>
	 * modelModelmanagerid: 模块关联的关联员id<br/>
	 * modelSort: 模块的排序<br/>
	 * modelIsmenu: 模块是否是菜单<br/>
	 * }</dd><br/>
	 */
	@ApiOperation(value = "更新模块表信息模块表")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "modelId", value = "模块的编号", required = true,paramType="query"),
			@ApiImplicitParam(name = "modelTitle", value = "模块的标题", required = true,paramType="query"),
			@ApiImplicitParam(name = "modelCode", value = "模块编码", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelId", value = "模块父id", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelUrl", value = "链接地址", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelDatetime", value = "发布时间", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelIcon", value = "模块图标", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelManagerId", value = "模块管理员Id", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelSort", value = "模块排序", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelIsMenu", value = "是否是菜单", required = false,paramType="query"),
			@ApiImplicitParam(name = "isChild", value = "菜单类型", required = false,paramType="query"),
			@ApiImplicitParam(name = "modelParentIds", value = "父级编号集合", required = false,paramType="query"),
	})
	@LogAnn(title = "更新模块表信息模块表",businessType= BusinessTypeEnum.UPDATE)
	@PostMapping("/update")
	@ResponseBody
	public ResultData update(@ModelAttribute @ApiIgnore  ModelEntity model, HttpServletResponse response,
							 HttpServletRequest request) {
		if (!StringUtil.checkLength(model.getModelTitle(), 2, 20)
				|| !StringUtil.checkLength(model.getModelCode(), 2, 20)) {
			return ResultData.build().error(getResString("err.length", getResString("model.title"), "2", "20"));
		}
		//判断图标是否为空，不为空去掉,图标地址中含有的“|”
		//空值判断
		if(!StringUtil.isBlank(model.getModelIcon())) {
			model.setModelIcon( model.getModelIcon().replace("|", ""));
		}
		//添加父级id集合
		ModelEntity parent = (ModelEntity) modelBiz.getEntity(model.getIntId());
		String parentIds="";
		if(parent != null) {
			if (parent.getModelParentIds() != null) {
				parentIds = parent.getModelParentIds() + "," + model.getModelId();
			} else {
				parentIds = model.getModelId() + "";
			}
		}
		model.setModelParentIds(parentIds);
		modelBiz.updateEntity(model);
		return ResultData.build().success(model.getId());
	}

}
